# 周婧雅的科研数据处理
# 对目录下面的分词文件进行词频统计
import codecs
import os


class AnalyseInfo:
    c: ''
    t: ''
    a: ''
    p: ''
    f: ''


def getCTA(str):
    sl = str.split(" ")
    c = ''
    t = ''
    a = ''
    for each in sl:
        r = each.strip('\n')
        if(r.startswith("C=")):
            c = r[2:]
        if(r.startswith("T=")):
            t = r[2:]
        if(r.startswith("A=")):
            a = r[2:]
    return c, t, a


def analyse(lines, resultC, resultCT, resultCTA):
    for eachLine in lines:
        c, t, a = getCTA(eachLine)
        if(c in resultC):
            resultC[c] = resultC[c]+1
        else:
            resultC[c] = 1

        if((c+"-"+t) in resultCT):
            resultCT[c+"-"+t] = resultCT[c+"-"+t]+1
        else:
            resultCT[c+"-"+t] = 1

        if((c+"-"+t+"-"+a) in resultCTA):
            resultCTA[c+"-"+t+"-"+a] = resultCTA[c+"-"+t+"-"+a]+1
        else:
            resultCTA[c+"-"+t+"-"+a] = 1


def resultPrint(result):
    for c in sorted(result):
        print(c+":"+str(result[c]))


def exportCsv(result, name):
    fout = open(name, 'w', encoding='utf8')
    s = ''
    for c in sorted(result):
        s = s+(c+","+str(result[c]))+'\n'

    fout.write(s)

    fout.close()


def getF(clist, result):
    r = {}

    for c in clist:
        oldkey = ''
        for k in result:
            if(k.startswith(c+"-")):
                if(oldkey != ''):
                    r[k] = result[k]
                    r[oldkey] = result[oldkey]
                oldkey = k

    return r


def analysefolder(path):
    resultC = {}
    resultCT = {}
    resultCTA = {}
    resultPrint(resultC)
    items = os.listdir(path)
    for item in items:
        item = os.path.join(path, item)
        if(os.path.isfile(item)):
            with open(item, 'r', encoding='utf') as f:
                ln = f.readlines()
                resultPrint(resultC)
                analyse(ln, resultC, resultCT, resultCTA)

    resultF = getF(resultC, resultCT)

    resultPrint(resultC)
    exportCsv(resultC, path + 'C.csv')
    resultPrint(resultCT)
    exportCsv(resultCT, path+'CT.csv')
    resultPrint(resultCTA)
    exportCsv(resultCTA, path + 'CTA.csv')
    print("mismatch")
    resultPrint(resultF)
    exportCsv(resultF, path + 'mismatch.csv')


analysefolder('D:\\tmp\\try\\')
